package cn.lvji.springboot.learn4.controller;

import cn.lvji.springboot.learn4.entity.Scenic;
import cn.lvji.springboot.learn4.repository.ScenicRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class ScenicController {
    private final ScenicRepository scenicRepository;

    @Autowired
    public ScenicController(ScenicRepository scenicRepository) {
        this.scenicRepository = scenicRepository;
    }

    @GetMapping("/scenics")
    public List<Scenic> list() {
        return scenicRepository.findAll();
    }

    @GetMapping("/scenic/search")
    public List<Scenic> search(String name) {
        return scenicRepository.findByName(name);
    }

    /**
     * 分页查询
     *
     * @param name 景区名
     * @return
     */
    @GetMapping("/scenic/page/search")
    public List<Scenic> pageSearch(String name) {
        return scenicRepository.pageByName(name, PageRequest.of(1, 10, Sort.by(Sort.Direction.DESC, "createTime")));
    }

    @PatchMapping("/scenic/closed/{id}")
    public String close(@PathVariable Long id) {
        scenicRepository.closedById(id);
        return "success";
    }

    @GetMapping("/scenic/")
    public Scenic get(String name, Long id) {
        return scenicRepository.findScenic(name, id);
    }

    /**
     * example 查询，可以结合ExampleMatcher
     *
     * @param name 景区名
     * @return
     */
    @GetMapping("/scenic/example")
    public Scenic get(String name) {
        Scenic scenic = new Scenic();
        scenic.setName(name);
        Example<Scenic> example = Example.of(scenic);
        return scenicRepository.findOne(example).get();
    }

}
